package com.si.sea_island.controller;

import com.si.sea_island.base.JsonResult;
import com.si.sea_island.base.ResultCode;
import com.si.sea_island.mapper.*;
import com.si.sea_island.pojo.UserDB;
import com.si.sea_island.pojo.sms.SmsDB;
import com.si.sea_island.utils.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Transactional//开启事务回滚
@Api(tags = "登录注册模块")
@Slf4j
public class LoginController {

    @Autowired
    VerifyMapper verifyMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    UserDBMapper userDBMapper;
    @Autowired
    SmsDBMapper smsDBMapper;
    @Autowired
    PrivacyEncryptionUtil privacyEncryptionUtil;
    @Autowired
    private IslandMapper islandMapper;
    @Autowired
    private ShopMapper shopMapper;

    /**
     * 自动注册科创互联
     * @param request phone电话  password密码
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "电话",required = true,paramType = "param"),
            @ApiImplicitParam(name = "privateKey",value = "密匙",required = true,paramType = "param"),
            @ApiImplicitParam(name = "directUserPhone",value = "直推用户电话",required = true,paramType = "param"),
            @ApiImplicitParam(name = "password",value = "密码",required = true,paramType = "param"),
            @ApiImplicitParam(name = "payPassword",value = "支付密码",required = true,paramType = "param"),
    })
    @ApiOperation(value = "自动注册海岛", notes = "自动注册海岛")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = UserDB.class)
    })
    @PostMapping("/api/automaticLogon")
    public JsonResult automaticLogon(HttpServletRequest request){
        //请求参数
        String phone = request.getParameter("phone");
        String privateKey = request.getParameter("privateKey");
        String directUserPhone = request.getParameter("directUserPhone");
        String password = request.getParameter("password");
        String payPassword = request.getParameter("payPassword");
        if (phone == null || privateKey == null || directUserPhone == null || password == null || payPassword == null) {
            return JsonResult.error(222,"缺少参数");
        }
        if ("".equals(privateKey)||"".equals(phone)||"".equals(directUserPhone)||"".equals(password)||"".equals(payPassword)){
            return JsonResult.error(222,"缺少参数");
        }

        //密匙校验
        if (!"SI20241212E9Hogjce55ftmk124GKy47o4mdsxXc2wl4FxaGPwbAQbLTqweW8".equals(privateKey)){
            return JsonResult.error(222,"密匙错误");
        }

        //设置用户信息
        UserDB user = userDBMapper.selectUserByPhone(phone);
        if(user!=null){
            return JsonResult.error(222,"用户已注册");
        }
        //设置新用户信息
        user = new UserDB();
        user.setUserName(phone);
        user.setPhone(phone);
        user.setNickName(phone);
        user.setPassword(passwordEncoder.encode(password));
        user.setPayPassword(payPassword);
        user.setCreateTime(DateUtils.getNowTime());
        user.setAvatar("http://www.qiyitong91.com/images/service/ic_r.jpg");
        //生成用户唯一标识
        String uniqueIdentification = RandomStringUtils.randomAlphanumeric(8);
        UserDB userDB = userDBMapper.getUserByUniqueIdentification(uniqueIdentification);
        while (userDB != null) {
            uniqueIdentification = RandomStringUtils.randomAlphanumeric(8);
            userDB = userDBMapper.getUserByUniqueIdentification(uniqueIdentification);
        }
        user.setUserUniqueIdentification(uniqueIdentification);

        //查询直推用户信息
        UserDB directUser = userDBMapper.selectUserByPhone(directUserPhone);
        if (directUser != null) {
            user.setDirectUid(String.valueOf(directUser.getId()));
            //设置间接推荐
            String indirectUid="";
            if (directUser.getIndirectUid()!=null&&!"".equals(user.getIndirectUid())){
                indirectUid= ","+directUser.getIndirectUid()+directUser.getId()+",";
            }else {
                indirectUid= ","+directUser.getId()+",";
            }
            user.setIndirectUid(indirectUid);
        }else {
            user.setDirectUid("");
            user.setIndirectUid("");
        }
        //用户注册
        userDBMapper.insertUserDB(user);



        return JsonResult.success("自动注册成功");
    }

    /**
     * 电话+密码登录
     * @param request phone电话  password密码
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "电话",required = true,paramType = "param"),
            @ApiImplicitParam(name = "password",value = "密码",required = true,paramType = "param")
    })
    @ApiOperation(value = "用户端电话+密码登录", notes = "用户登录")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = UserDB.class)
    })
    @PostMapping("/api/login")
    public JsonResult login(HttpServletRequest request){
        //请求参数
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        if (phone == null || password == null) {
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        UserDB userDB = userDBMapper.selectUserByPhone(phone);
        if (userDB == null) {
            return JsonResult.error(ResultCode.user_not_find,"用户不存在");
        }
        log.info("login--userDB--"+userDB.getId()+"--password--"+userDB.getPassword());
        if (!passwordEncoder.matches(password,userDB.getPassword())){
            return JsonResult.error(ResultCode.password_error,"密码错误");
        }
        int userId = userDB.getId();
//        //生成token
//        String token = TokenUtils.makeToken();
//        //储存token
//        VerifyDB verifyDB = new VerifyDB();
//        verifyDB.setToken(token);
//        verifyDB.setUid(userDB.getId());
//        verifyDB.setTime(DateUtils.getNowTime());
//        //判断是否已经有记录
//        VerifyDB verifyDB1 = verifyDBMapper.getVerifyDBById(userDB.getId());
//        if (verifyDB1==null){
//            verifyDBMapper.insertToken(verifyDB);
//        }else {
//            verifyDBMapper.updateToken(verifyDB);
//        }

        //生成token
        String token = JwtTokenUtil.createJwtToken(String.valueOf(userId),"user");
        String jwtRefreshToken = JwtTokenUtil.createJwtRefreshToken(String.valueOf(userId),"user");

        //返回token
        userDB.setToken(token);
        userDB.setJwtRefreshToken(jwtRefreshToken);

        //判断是否存在token记录
        String verify = verifyMapper.getVerifyDBById(userId,"0");
        if (verify==null){
            //生成新的token记录
            verifyMapper.saveToken(userId,token,DateUtils.getNowTime(),"0");
        }else {
            verifyMapper.updateToken(userId,token, DateUtils.getNowTime(),"0");
        }


        //私密信息加密
        userDB = new PrivacyEncryptionUtil().privacyEncryption(userDB);

        return JsonResult.success("登录成功").data(userDB);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "电话",required = true,paramType = "param"),
            @ApiImplicitParam(name = "checkV",value = "短信验证码",required = true,paramType = "param"),
            @ApiImplicitParam(name = "password",value = "密码",required = true,paramType = "param"),
            @ApiImplicitParam(name = "userUniqueIdentification",value = "邀请码",required = false,paramType = "param"),
            @ApiImplicitParam(name = "payPassword",value = "支付密码",required = false,paramType = "param"),
    })
    @ApiOperation(value = "用户端短信验证码登录注册", notes = "使用电话加短信验证码登录，如果没有账户就自动注册并登录，注册时密码必传")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = UserDB.class)
    })
    @PostMapping("/api/loginOrRegisterPhone")
    public JsonResult register(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        String userUniqueIdentification = request.getParameter("userUniqueIdentification");
        String payPassword = request.getParameter("payPassword");
        String checkV = request.getParameter("checkV")==null?"":request.getParameter("checkV");
        System.out.println("phone:"+phone);
        //检验手机号
        if (!WPhoneUtils.isChinaPhone(phone)) {
            return JsonResult.error(ResultCode.phone_format_error,"请填写正确的手机号");
        }
        if (phone==null||"".equals(phone)) {
            return JsonResult.error(ResultCode.phone_format_error,"手机号不能为空");
        }
        if (userUniqueIdentification==null||"".equals(userUniqueIdentification)) {
            return JsonResult.error(ResultCode.phone_format_error,"邀请码不能为空");
        }
        if (password==null||"".equals(password)) {
            password = "123456";
        }

        //短信校验
        SmsDB ordSmsDB = smsDBMapper.getSmsByPhone(phone);
        if (ordSmsDB == null) {
            return JsonResult.error(ResultCode.sms_not_send,"未发送短信到"+phone);
        }
        //短信时间校验
        if (System.currentTimeMillis() - Long.parseLong(ordSmsDB.getTime()) > 900000) {
            return JsonResult.error(ResultCode.sms_time_out,"验证码超时");
        }
        if (!ordSmsDB.getCode().equals(checkV)) {
            return JsonResult.error(ResultCode.sms_verify_error,"短信验证码错误");
        }

        //用户校验
        UserDB registerUserDB = userDBMapper.selectUserByUsername(phone);
        if (registerUserDB != null) {
            registerUserDB = userDBMapper.selectUserByUsername(phone);
            int userId = registerUserDB.getId();
            Map<String, String> map = new HashMap<>();
            //生成token
            String token = JwtTokenUtil.createJwtToken(String.valueOf(userId),"user");
            String jwtRefreshToken = JwtTokenUtil.createJwtRefreshToken(String.valueOf(userId),"user");

            //用户校验
            UserDB user = userDBMapper.selectUserByUsername(phone);
            user.setToken(token);

            //判断是否存在token记录
            String verify = verifyMapper.getVerifyDBById(userId,"0");
            if (verify==null){
                //生成新的token记录
                verifyMapper.saveToken(userId,token,DateUtils.getNowTime(),"0");
            }else {
                verifyMapper.updateToken(userId,token,DateUtils.getNowTime(),"0");
            }

            //私密信息加密
            user = privacyEncryptionUtil.privacyEncryption(user);

            return JsonResult.success("登录成功").data(user);
        }

        //判断是否有密码
        if(password==null||"".equals(password)){
            return JsonResult.error(ResultCode.phone_format_error,"密码不能为空");
        }


        //设置新用户信息
        registerUserDB = new UserDB();
        registerUserDB.setUserName(phone);
        registerUserDB.setPhone(phone);
        registerUserDB.setNickName(phone);
        registerUserDB.setPassword(passwordEncoder.encode(password));
        registerUserDB.setPayPassword(payPassword);
        registerUserDB.setCreateTime(DateUtils.getNowTime());
        registerUserDB.setAvatar("http://www.qiyitong91.com/images/service/ic_r.jpg");
        //生成用户唯一标识
        String uniqueIdentification = RandomStringUtils.randomAlphanumeric(8);
        UserDB userDB = userDBMapper.getUserByUniqueIdentification(uniqueIdentification);
        while (userDB != null) {
            uniqueIdentification = RandomStringUtils.randomAlphanumeric(8);
            userDB = userDBMapper.getUserByUniqueIdentification(uniqueIdentification);
        }

        registerUserDB.setUserUniqueIdentification(uniqueIdentification);


        //邀请码设置
        UserDB user = userDBMapper.selectUserByUserUniqueIdentification(userUniqueIdentification);
        if (user==null){
            return JsonResult.error(ResultCode.phone_format_error,"推荐码错误");
        }
        registerUserDB.setDirectUid(String.valueOf(user.getId()));
        //设置间接推荐
        String indirectUid="";
        if (user.getIndirectUid()!=null&&!"".equals(user.getIndirectUid())){
            indirectUid= user.getIndirectUid()+user.getId()+",";
        }else {
            indirectUid= ","+user.getId()+",";
        }
        if (indirectUid!=""){
            registerUserDB.setIndirectUid(indirectUid);
        }

        //用户注册
        userDBMapper.insertUserDB(registerUserDB);

        registerUserDB = userDBMapper.selectUserByUsername(phone);
        int userId = registerUserDB.getId();

        //用户校验
        user = userDBMapper.selectUserByUsername(phone);

        //生成token
        String token = JwtTokenUtil.createJwtToken(String.valueOf(userId),"user");
        String jwtRefreshToken = JwtTokenUtil.createJwtRefreshToken(String.valueOf(userId),"user");

        //返回token
        user.setToken(token);

        //判断是否存在token记录
        String verify = verifyMapper.getVerifyDBById(userId,"0");
        if (verify==null){
            //生成新的token记录
            verifyMapper.saveToken(userId,token,DateUtils.getNowTime(),"0");
        }else {
            verifyMapper.updateToken(userId,token,DateUtils.getNowTime(),"0");
        }

        //自动注册系列软件
        //获取直推用户电话
        UserDB directUser = userDBMapper.getUserById(Integer.parseInt(user.getDirectUid()));
        if (directUser==null){
            AutomaticLogonUtil.automaticLogon(phone,"0000",password,user.getPayPassword());
        }else {
            AutomaticLogonUtil.automaticLogon(phone,directUser.getPhone(),password,user.getPayPassword());
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        //批量插入海岛初始数据  3张中间表
          int islandNum = islandMapper.selectIslandNum();
          //海岛用户表批量插入
        for (int tid = 1; tid <= islandNum; tid++) {
            islandMapper.insertNewUser(tid,userId);
        }
          //用户食物表批量插入
        int foodNum = shopMapper.selectFoodNum();
        for (int fid = 1; fid <= foodNum; fid++) {
            shopMapper.insertNewUserFood(fid,userId);
        }
          //用户果实表批量插入
        int fruitNum = shopMapper.selectFruitNum();
        for (int fid = 1; fid <= fruitNum; fid++) {
            shopMapper.insertNewUserFruit(fid,userId);
        }
        stopWatch.stop();

        System.out.println("同步处理耗时" + stopWatch.getTotalTimeMillis()+"ms");

        //私密信息加密
        user = privacyEncryptionUtil.privacyEncryption(user);


        return JsonResult.success("注册成功,自动登录").data(user);
    }






}
